import { createSSRApp } from "vue";
import { install as installCore, UniNet } from "@ibiz-template/core";
import { install as installRuntime } from "@ibiz-template/runtime";
import MobTheme from "@ibiz-template/mob-theme";
import {
  OpenViewUtil,
  UnauthorizedHandler,
  attachEnvironmentConfig,
} from "@/utils";
import { store, useAppStore } from "@/store";
import { i18n, IBizI18n } from "@/locale";
import { AppHooks } from "@/hooks";
import { IBizComponents } from "@/components";
import { IBizViewEngine } from "@/view-engine";
import { RequestInterceptor, routeInterceptor } from "@/interceptors";
import App from "./App.vue";

export function createApp() {
  // 注册core
  installCore();
  // 注入环境参数
  attachEnvironmentConfig();
  // 注册runtime
  installRuntime();

  // 重新注册全局net
  ibiz.net = new UniNet();

  ibiz.util.getGlobalParam = () => {
    return useAppStore().appStore;
  };

  const app = createSSRApp(App);

  // 注册钩子
  AppHooks.useComponent.tap((_: null, plugin: any): void => {
    app.use(plugin);
  });
  app.use(MobTheme);
  // Pinia注册
  app.use(store);
  // 拦截器注册
  app.use(routeInterceptor);
  app.use(RequestInterceptor);
  // i18n注册
  app.use(i18n);
  // 组件注册
  app.use(IBizComponents);
  // 视图引擎注册
  app.use(IBizViewEngine);

  ibiz.i18n = new IBizI18n();
  ibiz.i18n.init();

  // 注册错误处理器
  ibiz.util.error.register(new UnauthorizedHandler());
  // 全局异常处理
  uni.onError((err: unknown) => {
    ibiz.util.error.handle(err);
  });

  ibiz.openView = new OpenViewUtil();

  return {
    app,
  };
}
